"""
登录页面对象类
"""
import logging
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from tests.page_objects.base_page import BasePage


class LoginPage(BasePage):
    """登录页面的页面对象模型"""
    
    # 页面元素定位器 - 基于Vue代码更新
    USERNAME_INPUT = (By.CSS_SELECTOR, "input[placeholder='请输入用户名']")
    PASSWORD_INPUT = (By.CSS_SELECTOR, "input[placeholder='请输入密码']")
    
    # 根据用户提供的HTML代码更新登录按钮定位器
    LOGIN_BUTTON = (By.CSS_SELECTOR, "button.el-button.el-button--primary.auth-button")
    LOGIN_BUTTON_ALT1 = (By.XPATH, "//button[contains(@class, 'el-button--primary') and .//span[text()='登录']]")
    LOGIN_BUTTON_ALT2 = (By.XPATH, "//button[.//span[text()='登录']]")
    LOGIN_BUTTON_ALT3 = (By.CSS_SELECTOR, ".el-form-item__content button")
    
    REGISTER_LINK = (By.CSS_SELECTOR, ".register-link")
    WELCOME_TEXT = (By.CSS_SELECTOR, ".welcome-text")
    FORM_DESC = (By.CSS_SELECTOR, ".form-desc")
    
    # 消息提示元素 - 根据Element Plus组件特性
    ERROR_MESSAGE = (By.CSS_SELECTOR, ".el-message--error")
    FORM_ERROR_MESSAGE = (By.CLASS_NAME, "el-form-item__error")
    SUCCESS_MESSAGE = (By.CSS_SELECTOR, ".el-message--success")
    
    # 页面URL
    LOGIN_URL = "http://localhost:8080/login"
    
    def __init__(self, driver):
        """
        初始化登录页面对象
        
        Args:
            driver: WebDriver实例
        """
        super().__init__(driver)
        self.wait = WebDriverWait(self.driver, 10)
        
    def open_login_page(self):
        """
        打开登录页面
        """
        logging.info(f"打开登录页面: {self.LOGIN_URL}")
        self.driver.get(self.LOGIN_URL)
        # 等待页面加载完成
        time.sleep(2)
        self.wait_for_page_load()
        return self
        
    def enter_username(self, username):
        """
        输入用户名
        
        Args:
            username: 要输入的用户名
        """
        logging.info(f"输入用户名: {username}")
        # 等待用户名输入框可见
        username_input = self.wait.until(EC.visibility_of_element_located(self.USERNAME_INPUT))
        username_input.clear()
        username_input.send_keys(username)
        return self
        
    def enter_password(self, password):
        """
        输入密码
        
        Args:
            password: 要输入的密码
        """
        logging.info(f"输入密码: {'*' * len(password)}")
        # 等待密码输入框可见
        password_input = self.wait.until(EC.visibility_of_element_located(self.PASSWORD_INPUT))
        password_input.clear()
        password_input.send_keys(password)
        return self
        
    def click_login_button(self):
        """
        点击登录按钮
        """
        logging.info("点击登录按钮")
        
        # 简化登录按钮点击，只使用主要选择器
        try:
            if self.is_element_present(self.LOGIN_BUTTON):
                self.click(self.LOGIN_BUTTON)
                return self
        except Exception as e:
            logging.warning(f"使用主要选择器点击登录按钮失败: {e}")
        
        # 备用选择器
        try:
            if self.is_element_present(self.LOGIN_BUTTON_ALT1):
                self.click(self.LOGIN_BUTTON_ALT1)
                return self
        except Exception as e:
            logging.warning(f"使用备用选择器点击登录按钮失败: {e}")
        
        # 最后尝试JavaScript点击
        try:
            self.driver.execute_script("document.querySelector('button.el-button').click();")
            logging.info("使用JavaScript点击登录按钮成功")
        except Exception as e:
            logging.error(f"点击登录按钮失败: {e}")
        
        return self
        
    def press_enter_to_login(self):
        """
        按回车键登录（根据Vue代码中的@keyup.enter事件）
        """
        logging.info("按回车键登录")
        self.find_element(self.PASSWORD_INPUT).send_keys(Keys.ENTER)
        return self
        
    def click_register_link(self):
        """
        点击注册链接
        """
        logging.info("点击注册链接")
        self.click(self.REGISTER_LINK)
        return self
        
    def login(self, username, password):
        """
        执行登录操作
        
        Args:
            username: 用户名
            password: 密码
        """
        logging.info(f"执行登录操作: 用户名={username}")
        self.enter_username(username)
        self.enter_password(password)
        self.click_login_button()
        
        # 减少等待时间
        time.sleep(0.5)
        
        # 简化验证逻辑，只做基本检查
        current_url = self.driver.current_url
        if self.LOGIN_URL not in current_url:
            logging.info(f"URL已发生变化，当前URL: {current_url}")
            return True
        else:
            logging.info(f"URL未变化，仍在登录页面: {current_url}")
            return False
    
    def login_with_enter(self, username, password):
        """
        使用回车键执行登录操作
        
        Args:
            username: 用户名
            password: 密码
        """
        logging.info(f"使用用户名 {username} 和回车键登录")
        return (self
                .enter_username(username)
                .enter_password(password)
                .press_enter_to_login())
        
    def get_welcome_text(self):
        """
        获取欢迎文本
        
        Returns:
            欢迎文本
        """
        return self.get_text(self.WELCOME_TEXT)
    
    def get_form_description(self):
        """
        获取表单描述文本
        
        Returns:
            表单描述文本
        """
        return self.get_text(self.FORM_DESC)
        
    def get_error_message(self):
        """
        获取错误消息
        
        Returns:
            错误消息文本列表
        """
        try:
            # 首先检查表单错误信息（输入框下方的验证错误）
            error_elements = self.find_elements(self.FORM_ERROR_MESSAGE)
            error_messages = [element.text for element in error_elements if element.text.strip()]
            
            # 如果有表单错误信息，直接返回
            if error_messages:
                logging.info(f"获取到表单错误信息: {error_messages}")
                return error_messages
            
            # 其次检查全局错误信息（顶部弹出的消息）
            if self.is_element_present(self.ERROR_MESSAGE):
                global_error = self.get_text(self.ERROR_MESSAGE)
                if global_error:
                    logging.info(f"获取到全局错误信息: {global_error}")
                    return [global_error]
            
            # 如果没有找到任何错误信息，返回空列表
            logging.warning("未找到任何错误信息")
            return []
        except Exception as e:
            logging.error(f"获取错误信息失败: {e}")
            return []
        
    def get_success_message(self):
        """
        获取成功消息
        
        Returns:
            成功消息文本
        """
        if self.is_element_present(self.SUCCESS_MESSAGE):
            return self.get_text(self.SUCCESS_MESSAGE)
        return ""
        
    def is_login_successful(self):
        """
        检查登录是否成功
        
        Returns:
            布尔值，表示登录是否成功
        """
        # 只检查URL是否不再包含登录页面路径
        current_url = self.driver.current_url
        logging.info(f"检查登录是否成功，当前URL: {current_url}")
        
        # 如果URL不包含login，则认为登录成功
        if "/login" not in current_url and "/back/" in current_url:
            logging.info("登录成功：URL已跳转到后台页面")
            return True
        else:
            logging.warning("登录可能失败：URL未跳转到后台页面")
            return False
    
    def is_validation_error_shown(self, field):
        """
        检查表单验证错误是否显示
        
        Args:
            field: 字段名称 ('username' 或 'password')
            
        Returns:
            布尔值，表示是否显示了验证错误
        """
        if field == 'username':
            return self.is_element_present((By.XPATH, "//form//div[contains(@class, 'el-form-item__error') and contains(text(), '请输入用户名')]"))
        elif field == 'password':
            return self.is_element_present((By.XPATH, "//form//div[contains(@class, 'el-form-item__error') and contains(text(), '请输入密码')]"))
        return False 